require(['common', 'request'], function (common, Request) {
    // 渲染顶部菜单
    function renderTopMenu(menus) {
        if (menus && menus.length > 0) {
            for (var i = 0; i < menus.length; i++) {
                var $li = $('<li></li>');
                $li.addClass('admin-nav-item');
                $li.append('<a class="admin-tab-menu-a">' + menus[i].title + '</a>');
                $li.data('menu', menus[i].children);
                $('#admin-tab-menu').append($li);
                if (menus[i].spread) {
                    renderNav($li);
                }
            }
            // 如果没有默认展开的菜单，默认展开第一个
            if ($('#admin-tab-menu .admin-nav-selected').length == 0) {
                var navIndex = $.cookie("navIndex") ? $.cookie("navIndex") : 1;
                renderNav($('#admin-tab-menu .admin-nav-item:nth-child('+navIndex+')'));
                var leftNavOne = $.cookie("leftNavOne");
                leftNavOne ? admintab.tabAdd(JSON.parse(leftNavOne)) : false;
            }
            // 菜单可用宽度
            var vW = $('.admin-main').width() - $('.admin-login-box').width() - $('.admin-header-item').width() - 80;
            // 菜单实际宽度
            var mW = $('#admin-tab-menu').width();
            // 如果菜单过多，缩小每个菜单的宽度。
            if (vW - mW < 0) {
                $('#admin-tab-menu .admin-nav-item a').width(Math.floor(vW / menus.length));
            }
        }
    }

    // 渲染左侧菜单
    function renderNav(target) {
        if (target.hasClass('admin-nav-selected')) {
            return;
        } else {
            $('#admin-tab-menu .admin-nav-selected').removeClass('admin-nav-selected');
            target.addClass('admin-nav-selected');
        }
        //渲染navbar
        navbar.render({
            spreadOne: true,
            elem: '#admin-navbar-side',
            cached: true,
            data: target.data('menu')
        });
        var leftNavOne = $.cookie("leftNavOne");
        if(leftNavOne){
            admintab.tabAdd(leftNavOne);
        }
        navbar.on('click', function (data) {
            admintab.tabAdd(data.field);
            $.cookie("leftNavOne",JSON.stringify(data.field));
        });
    }

    (function () {
        var req = new Request("api/current/user/info");
        req.get({
            isErrorTip: false,
            success: function (data) {
                // 保存人员信息到顶层中
                common.getTopWindowDom().userInfo = data;
                $("#lab-user-name").text(data["realName"]);
            }
        });
        admintab.init({
            elem: '.admin-tab',
            contextMenu: true
        });
        var req = new Request("api/sys/menu/tree");
        req.get({
            data: {
                fkSystem: '001'
            },
            success: function (d) {
                if (d.code == '0' && d.result.length > 0) {
                    renderTopMenu(d.result);
                }
            }
        });

        //顶部菜单栏点击
        $('#admin-tab-menu').on('click', 'li.admin-nav-item', function () {
            var navIndex = $('#admin-tab-menu li').index(this)+1;   //获取navbar的节点下标
            navIndex = navIndex ? navIndex : 1;
            $.cookie("navIndex",navIndex);
            $.cookie("leftNavOne","");
            renderNav($(this));
        });

        //左侧横向展开和折叠
        $('#toggleSide').click(function () {
            //admin-footer admin-footer-toggle admin-body  admin-body-toggle admin-side admin-side-toggle
            $('.admin-side').toggleClass('admin-side-toggle');
            $('.admin-body').toggleClass('admin-body-toggle');
            $("#toggleSide").toggleClass('arrow-o-right arrow-o-left');
            if ($('.admin-side').hasClass('admin-side-toggle')) {
                $('.admin-side-scroll').css({'overflow-y': 'visible'});
            } else {
                $('.admin-side-scroll').css({'overflow-y': 'auto'});
            }
        });

        // 修改密码
        $('#btn-update-pwd').click(function () {
            var dialogParam = {
                title: '修改密码',
                content: GLOBAL_WEB_BASE_PATH + "/sys/user/password.html",
                area: ["330px", "270px"],
                btn: ['保存', '关闭'],
                btn1: function (dialogIndex, dialogDom) {
                    var top = common.getTopWindowDom();
                    var page = dialogDom.find('iframe')[0].contentWindow.__password_win;
                    page.postData(function () {
                        $(dialogDom).find(".layui-layer-btn0").text("保存中...");
                    }, function (data) {
                        $(dialogDom).find(".layui-layer-btn0").text("保存");
                        if (data.code == 0) {
                            top.layer.close(dialogIndex);
                        }
                    });
                }
            };
            common.dialog(dialogParam);
        });

        $('#btn-login-out').on("click", function () {
            // alert("是否退出当前登录用户？");
            common.confirm({
                ok: "退出",
                cancel: '取消',
                text: "是否退出当前登录用户？",
                callback: function (result) {
                    if (result) {
                        var req = new Request("api/current/logout?access_token=" + $.cookie('access_token'));
                        req.get({
                            isErrorTip: false,
                            success: function (data) {
                                //当状态等于1的时候表示退出成功
                                if (data.code == "0"){
                                    window.location.href = GLOBAL_WEB_BASE_PATH + "/login.html";
                                }
                                $.cookie("navIndex","");
                                $.cookie("dataId", "");
                                $.cookie("leftNavOne", "");
                            }
                        })
                    }
                }
            })
        });
        $(window).on('resize', function () {
            var $content = $('.admin-tab .admin-tab-content');
            $content.height($(this).height() - 105);
            $content.find('iframe').each(function () {
                $(this).height($content.height());
            });
        }).resize();

        /**
         * 修改个人信息
         */
        $('#btn-update-userinfo').click(function () {
            var dialogParam = {
                title: '修改个人信息',
                content: GLOBAL_WEB_BASE_PATH + "/sys/user/userinfo.html",
                area: ["320px", "340px"],
                btn: ['保存', '关闭'],
                btn1: function (dialogIndex, dialogDom) {
                    var top = common.getTopWindowDom();
                    var page = dialogDom.find('iframe')[0].contentWindow.__userinfo_win;
                    page.postData(function () {
                        $(dialogDom).find(".layui-layer-btn0").text("保存中...");
                    }, function (data) {
                        $(dialogDom).find(".layui-layer-btn0").text("保存");
                        if (data.code == 0) {
                            top.layer.close(dialogIndex);
                        }
                    });
                }
            };
            common.dialog(dialogParam);
        });

    })();
});

